<?php

require_once APPLICATION_PATH . '/../library/ckeditor/ckeditor.php';

class Admin_BlogController extends GTL_Action {

    public function init() {
        parent::init();
        /* Initialize action controller here */
        $this->list_sess_unset('controller_blog');
        $this->session_search_key = 'controller_blog';
        $this->session_search_name = 'search_label';
    }

    public function indexAction() {
        $this->_helper->redirector('list', 'blog', 'admin');
    }

    public function viewAction() {
        $this->view->blogalldata = $blogalldata;
        if ($this->_getParam('blog_id') && $this->_getParam('blog_id') != '') {
            $blog_id = $this->_getParam('blog_id');
        } else {
            $this->_helper->redirector('list', 'blog', 'admin');
            $blogModel = new Model_Blog();
            $blogalldata = $blogModel->fetchEntryById($blog_id);
        }
    }

     public function uploadAction() {
        
        $upload = new Zend_File_Transfer_Adapter_Http();
        
        foreach ($upload->getFileInfo() as $fields => $asFileInfo) {
            
            if ($asFileInfo['name'] != '') {
                
                if ($this->getRequest()->isPost()) {
                    
                    $postedData = $this->_request->getPost();
                    if ($postedData['UNIQUEIDENTIFIER'] != '') {
                        $folder = $this->config->UPLOAD_PATH . "blog/multiimage/";
                        $upload->setDestination($folder);
                        $originalFilename = pathinfo($asFileInfo['name']);
                        $file_name = preg_replace("/[^-_a-zA-Z0-9]+/i", "_", $originalFilename['filename']) . '_' . time() . '.' . $originalFilename['extension'];
                        $upload->addFilter('Rename', $file_name, 'filename');
                        $upload->receive($fields);
                        $ImageModel = new Model_Blogimage();
                        $ImageArray = array();
                        $ImageArray['im_blog_id'] = '';
                        $ImageArray['im_identifier'] = $postedData['UNIQUEIDENTIFIER'];
                        $ImageArray['im_name'] = $file_name;
                        $ImageArray['im_image_name'] = $asFileInfo['name'];
                        $ImageArray['im_status'] = 1;
                        $ImageArray['im_createddate'] = date('Y-m-d H:i:s');
                        $ImageModel->save($ImageArray, 'im_id');
                       
                    }
                }
            }
        }

    }

   
    
    public function listAction() {
        $errorMessage = Array();
        $successmessage = '';
        $where = '';
        $searchtype = '';
        $orderField = 'blog_id';
        $sort = 'desc';
        

        /* Pagination Login */
        $itemsPerPageReviews = $this->view->PAGING_PER_PAGE;
        $currentPageReviews = 1;



        //PAGING_PER_PAGE
        if ($this->_getParam('page') && $this->_getParam('page') != '') {
            $currentPageReviews = $this->_getParam('page');
        }

        if ($this->_getParam('field') && $this->_getParam('field') != '') {
            $orderField = $this->_getParam('field');
        }

        if ($this->_getParam('sort') && $this->_getParam('sort') != '') {
            $sort = $this->_getParam('sort');
        }
        $offset = ($currentPageReviews - 1) * $itemsPerPageReviews;

        if ($this->_request->isPost()) {

            $postedData = $this->_request->getPost();
            
           

            //Multiple Delete Logic 
            if (isset($postedData['multiaction']) && ($postedData['multiaction'] != '')) {
                $action = trim($postedData ['multiaction']);
                if (isset($postedData['multicheck']) && count($postedData['multicheck']) > 0) {
                    $ids = implode(',', $_POST['multicheck']);
                    $result = $this->deleteAction($_POST['multicheck']);
                } else {
                    $errorMessage[] = ' Please select atleast one checkbox! ';
                }
            }


            /* search code here */
            if ($postedData['searchtype'] == '') {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = '';
            }
            if (isset($postedData['searchtype']) && ($postedData['searchtype'] != '')) {
                $searchtype = $postedData['searchtype'];
                $where = " blog_title LIKE '%$searchtype%' OR blog_shortdescription LIKE '%$searchtype%' OR cat_name LIKE '%$searchtype%'  OR blog_status LIKE '%$searchtype%' ";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = $searchtype;
                $this->view->searchtype = $searchtype;
            }
        } else {

            if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name])) {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = '';
            }
            $searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
            $where = " blog_title LIKE '%$searchtype%'   OR blog_shortdescription LIKE '%$searchtype%' OR cat_name LIKE '%$searchtype%'  OR blog_status LIKE '%$searchtype%' ";
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = $searchtype;
            $this->view->searchtype = $searchtype;
        }

        $blogModel = new Model_Blog();
        //$referenceModel = new Model_Reference();

        $blogsData = $blogModel->fetchBlog($where, $itemsPerPageReviews, $offset, $orderField, $sort);

        $paginator = new GTL_Paginator();
        $paginator->setItemsPerPage($itemsPerPageReviews);
        $paginator->setItemsTotal($blogModel->getBlogCount($where));
        $paginator->setCurrentPage($currentPageReviews);
        $link = $this->view->url(array('module' => 'admin', 'controller' => 'blog', 'action' => 'list', 'page' => 'PAGENO'), null, false);
        $paginator->paginate($link);
        $GTLOBJ = new GTL_Common();
        
        $this->view->gtlObj = $GTLOBJ;
        $this->view->paginator = $paginator;

        $this->view->blogsData = $blogsData;
        $this->view->errorMessage = $errorMessage;
        $this->view->successmessage = $successmessage;
        $this->view->statusArray = $blogModel->getStatusArray();
        $this->view->searchtype = $searchtype;
    }

    public function deleteAction($ids = Array()) {
        //Load blog Model 
        $blogModel = new Model_Blog();
        //$referenceModel = new Model_Reference();
        if ($this->_getParam('blog_id') && $this->_getParam('blog_id') != '') {
            $blog_id = $this->_getParam('blog_id');
            //$referenceModel->delete("bt_blog_id = " . $blog_id); //delete tad in tbl_blog_tag
            $blogModel->deleteBlog($blog_id);
            $this->addSuccessMessage('Record Successfully Deleted');
            $this->_helper->redirector('list', 'blog', 'admin');
        } else {
            $blogModel->deleteBlog($ids);
            $this->addSuccessMessage('Record Successfully Deleted');
            $this->_helper->redirector('list', 'blog', 'admin');
        }
    }

    public function deleteimageAction() {
        $ImageModel = new Model_Blogimage();
        if ($this->_getParam('id') && $this->_getParam('id') != "") {
            $id = $this->_getParam('id');
        }
        
        $imageData = $ImageModel->fetchEntryByimageId($id);
        
        $folder = $this->config->UPLOAD_PATH . "blog/multiimage/";
      
        $blog_image = $folder . $imageData['im_name'];
        
        if (file_exists($blog_image)) {
            @unlink($blog_image);
        }
        
        $ImageModel->delete("im_id = " . $id);
        $this->addSuccessMessage('Image Successfully Deleted');
        $this->_helper->redirector('list', 'blog', 'admin');
        exit;                    
    }
    public function formAction() {
        //Initialize
        $successmessage = '';
        //$bt_id = '';
        $bt_tag_id = '';
        //$bt_blog_id = '';
        //$bt_status = '';
        $imageName = '';
        $errorMessageArray = Array();
        $data = array();
        $blogData = Array();
        //$tagData = Array();
        $uniqueId = uniqid('unq_');
        $this->view->mode = 'Add';

        //Load blog Model
        $blogModel = new Model_Blog();
        //$referenceModel = new Model_Reference();


        //Load blog Form
        $blogForm = new Form_Admin_BlogForm();

        //Load the status array for the select box in form 
        $statusArray = $blogModel->getStatusArray();
        $blogForm->blog_status->addMultiOptions($statusArray);

        //Load the status array for the select box in form
        $categoryArray = $blogModel->getCategoryArray();
        $blogForm->blog_cat_id->addMultiOptions($categoryArray);

        //Load the status array for the multiple select box in form
        //$tagArray = $blogModel->getTagArray();
        //$blogForm->bt_tag_id->addMultiOptions($tagArray);


        //Check for the blog Parameter
        $blogData['blog_id'] = $this->_request->getParam('blog_id');
        $blog_id = (!empty($blogData['blog_id'])) ? $blogData['blog_id'] : null;

        //$ImageModel = new Model_Blogimage();
     
        if (!empty($blog_id)) {
            //Set the Mode to Edit
            $this->view->mode = 'Edit';
            //Fetch data to be loaded in form 
            $data = $blogModel->fetchEntryById($blog_id);
            $imageName = $data['blog_image'];
			
			//print_r($imageName);exit;
            //$refTagData = $referenceModel->fetchtagreference($blog_id);
            //$data['bt_tag_id'] = $refTagData;
            //$imageData = $ImageModel->fetchEntryById($blog_id);
            //$this->view->blogImage = $imageData;
            
        }

        //Populate form 
        $this->view->form = $blogForm->populate($data);
        if ($this->getRequest()->isPost()) {
             $postedData = $this->_request->getPost();
                
             /*if ($postedData['UNIQUEIDENTIFIER'] != '') {
                $uniqueId = $postedData['UNIQUEIDENTIFIER'];
            }*/
            //image validation
            if ($_FILES['blog_image']['name'] != '') {
                $gtlObj = new GTL_Common();
                $imageAllowedFormat = $gtlObj->allowedImageFormats();
                $responseText = $gtlObj->image_validate($imageAllowedFormat, 'blog_image');
                if ($responseText == 'IMPROPER_FORMAT') {
                    $errorMessageArray[] = 'Please upload image with valid file format.';
                }
            }

            //Check for Errors
            
            if (!$blogForm->isValid($postedData)) {

                $errorMessage = $blogForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {

                if (count($errorMessageArray) > 0) {
                    
                } else {

                    if ($this->view->mode == 'Edit') {
                        if ($_FILES['blog_image']['name'] != '') {

                            $folder = $this->config->UPLOAD_PATH . "blog/";
                            $blog_image = $folder . $data['blog_image'];

                            if (file_exists($blog_image)) {
                                @unlink($blog_image);
                            }
                        }
                    }

                    // image upload
                    $upload = new Zend_File_Transfer_Adapter_Http();
                    foreach ($upload->getFileInfo() as $fields => $asFileInfo) {
                        if ($asFileInfo['name'] != '') {
                            $folder = $this->config->UPLOAD_PATH . "blog/";
                            $upload->setDestination($folder);
                            $originalFilename = pathinfo($asFileInfo['name']);
                            $fileName = preg_replace("/[^-_a-zA-Z0-9]+/i", "_", $originalFilename['filename']) . '_' . time() . '.' . $originalFilename['extension'];
                            $upload->addFilter('Rename', $fileName, 'filename');
                            $upload->receive($fields);
                            $blogData['blog_image'] = $fileName;
                        }
                    }

                    if ($this->view->mode == 'Add') {
                        $blogData['blog_createddate'] = date('Y-m-d H:i:s');
                    }
                    //blog save
                    $blogData['blog_id'] = $blog_id;
                    $blogData['blog_title'] = $postedData['blog_title'];
                    $blogData['blog_shortdescription'] = $postedData['blog_shortdescription'];
                    $blogData['blog_description'] = $postedData['blog_description'];
                    //$blogData['blog_video'] = $postedData['blog_video'];
                    $blogData['blog_cat_id'] = $postedData['blog_cat_id'];
                    $blogData['blog_updateddate'] = date('Y-m-d H:i:s');
                    $blogData['blog_status'] = $postedData['blog_status'];
																
							/*echo'<pre>';
							print_r($postedData);
							exit;*/
							
                    $blog_id = $blogModel->save($blogData, 'blog_id');
					
                     /* update blog id in blogimage table when upload image using dropzone*/    
                    
                     //$ImageModel->update(Array('im_blog_id' => $blog_id), "im_identifier = '" . $uniqueId . "'");
                    
                    /* delete tag data in edit time in from tbl_blog_tag */
                    //$referenceModel->delete("bt_blog_id = " . $blog_id);
                    
                    
                    /* save tag data in reference table */
                    /*if (array_key_exists('bt_tag_id', $postedData)) {
                        foreach ($postedData['bt_tag_id'] as $key => $value) {
                            $tagData['bt_id'] = NULL;
                            $tagData['bt_blog_id'] = $blog_id;
                            $tagData['bt_tag_id'] = $value;
                            $tagData['bt_updateddate'] = date('Y-m-d H:i:s');
                            $tagData['bt_createddate'] = date('Y-m-d H:i:s');
                            $tagData['bt_status'] = "1";
                            $referenceModel->save($tagData, 'bt_id');
                        }
                    }*/

                    if ($this->view->mode == 'Add') {
                        $successmessage = 'Blog add successfully';
                    } else {
                        $successmessage = 'Blog updated successfully';
                    }
                    $this->addSuccessMessage($successmessage);
                    $this->_helper->redirector('list', 'blog', 'admin');
                }
            }
        }
        $this->view->UNIQUEIDENTIFIER = $uniqueId;
        //$this->view->bt_id = $bt_id;
        $this->view->blogid = $blog_id;
        $this->view->imageName = $imageName;//print_r($imageName);exit;
        $this->view->errorMessageArray = $errorMessageArray;
        $this->view->succesMessage = $successmessage;
        $this->view->form = $blogForm;
    }

}

?>